package fr.softeam.modelio.task.reporting;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DownLoadReportingLauncher {
	
    static Logger logger = LoggerFactory.getLogger(DownLoadReportingLauncher.class);


	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		
		if(args.length < 1) {
			logger.error("This program must have file name in parameter");
			return ;
		}
		
		
		
		
		
		HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
		httpclient.getParams()
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
		
        httpclient.start();
        try {
        HttpGet[] requests = DownLoadReportingUtil.populatesGetRequests(DownLoadReportingUtil.fetchingUrlsFromFile(args[0]));
		final CountDownLatch latch = new CountDownLatch(requests.length);
		
        
        for (final HttpGet request: requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
        System.out.println("Done");

        
     
    }catch (IOException e) {
    	logger.error(e.getMessage());	}
        
        finally {
        httpclient.shutdown();
    }


	}

}
